package com.demon.minio.utils;

import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: TODO
 * @author: Mr.wu
 * @date: 2022年07月27日 14:04
 */
public class FileUtils {

    private static final Double MB = 1024.0 * 1024.0;

    private static final Double DEFAULT_SLICE = 10 * MB;

    /**
     * 文件分片
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static List<byte[]> sliceWithFile(MultipartFile file) throws IOException {
        if (ObjectUtils.isEmpty(file)||file.getBytes().length==0) {
            throw new RuntimeException("文件大小不能为空");
        }
        return slice(file.getBytes());
    }


    /**
     * 文件分片
     *
     * @param file
     * @return
     */
    public static List<byte[]> slice(byte[] file) throws FileNotFoundException {
        List<byte[]> bytesList = new ArrayList<>();
        if (ObjectUtils.isEmpty(file) || file.length <= 0) {
            return bytesList;
        }
        int sliceSize = (int) Math.ceil(Math.ceil(Double.valueOf(file.length) / DEFAULT_SLICE));
        byte[] bytes = null;
        for (int i = 0; i < sliceSize; i++) {
            if (i == sliceSize - 1 && sliceSize != 1) {
                //n片的最后一片
                int lastByteArrLength = file.length - ((sliceSize - 1) * DEFAULT_SLICE.intValue());
                bytes = new byte[lastByteArrLength];
                System.arraycopy(file, i * DEFAULT_SLICE.intValue(), bytes, 0, lastByteArrLength);
                bytesList.add(bytes);
                break;
            } else if (sliceSize == 1) {
                //仅1片
                bytesList.add(file);
                break;
            }
            bytes = new byte[DEFAULT_SLICE.intValue()];
            System.arraycopy(file, i * DEFAULT_SLICE.intValue(), bytes, 0, DEFAULT_SLICE.intValue());
            bytesList.add(bytes);
        }
        return bytesList;
    }

}
